package com.qch.edu.lagou.algorithm.half;

/**
 * @Author qch
 * @Date 2021/7/14
 * 二分法
 */
public class BinarySearch {
    /**
     * 普通二分查找法
     * @param nums
     * @param n
     * @return
     */
    public static int binarySearchCommon(int[] nums, int n) {
        //低位索引
        int low = 0;
        //高位索引
        int high = nums.length - 1;
        //中间索引
        int mid = 0;
        while (low <= high) {
            mid = (low + high) / 2;
            if (nums[mid] == n) {
                return mid;
            } else if (n > nums[mid]) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] nums={1,3,5,7,9,12,15,18,20};
        System.out.println(binarySearchCommon(nums,18));
    }
}
